 #pragma once
#include <iostream>
#include <sys/epoll.h>
#include <unistd.h>
#include "Command.hpp"
#include "Log.hpp"
using namespace LogModule;
class Epoller
{
public:
    Epoller()
        : _epfd(-1)
    {
        _epfd = epoll_create(126);
        if (_epfd < 0)
        {
            LOG(LogLevel::FATAL) << "epoll error ";
            exit(EPOLL_CREAT_ERR);
        }
        LOG(LogLevel::INFO) << "creat epoll sucess..."<<_epfd;
    }
    ~Epoller()
    {
        if (_epfd >= 0)
            close(_epfd);
    }

    void AddEvent(int sockfd, uint32_t event)
    {
        struct epoll_event ev;
        ev.events = event;
        ev.data.fd = sockfd; 
        int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, sockfd, &ev);
        if (n < 0)
        {
            LOG(LogLevel::ERROR) << "epoll_ctl error";
            return;
        }
        LOG(LogLevel::INFO) << "epoll_ctl success: " << sockfd;
    }
    void DelEvent(int sockfd)
     {
        int n = epoll_ctl(_epfd,EPOLL_CTL_DEL, sockfd, nullptr);
        (void)n;
     }
    void ModEvent(int sockfd,uint16_t newevent)
     {
        struct epoll_event ev;
        ev.events=newevent;
        ev.data.fd=sockfd;
        int n=epoll_ctl(_epfd,EPOLL_CTL_MOD,sockfd,&ev);
         if (n < 0)
        {
            LOG(LogLevel::ERROR) << "epoll_ctl error";
            return;
        }
        LOG(LogLevel::INFO) << "epoll_ctl success: " << sockfd;
     }
    int WaitEvent(struct epoll_event* revs,int maxnum,int timeout)
    {
       int n = epoll_wait(_epfd, revs, maxnum, timeout);
        if (n < 0)
        {
            LOG(LogLevel::WARNING) << "epoll_wait error";
        }
        else if (n == 0)
        {
            LOG(LogLevel::WARNING) << "epoll_wait timeout";
        }
        else
        {
            // TODO
        }

        return n;
    }

private:
    int _epfd;
public:
};